﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary.Statistics
{
    /// <summary>
    /// This class provides the computation of the Pearson correlation coefficient.
    /// </summary>
    [Serializable]
    public class PearsonCorrelation
    {
        /// <summary>
        /// The x vector for the correlation check.
        /// </summary>
        private GeneralVector x;

        /// <summary>
        /// The y vector for the correlation check.
        /// </summary>
        private GeneralVector y;

        /// <summary>
        /// Initializes a new instance of the <see cref="PearsonCorrelation"/> class.
        /// </summary>
        /// <param name="x">The x vector for the correlation check.</param>
        /// <param name="y">The y vector for the correlation check.</param>
        public PearsonCorrelation(GeneralVector x, GeneralVector y)
        {
            if (x == (GeneralVector) null)
            {
                throw new ArgumentNullException("x");
            }

            if (y == (GeneralVector) null)
            {
                throw new ArgumentNullException("y");
            }

            this.x = x;
            this.y = y;
        }

        /// <summary>
        /// Gets or sets the x vector for the correlation check.
        /// </summary>
        /// <value>The x vector for the correlation check.</value>
        public GeneralVector X
        {
            get { return this.x; }
            set { this.x = value; }
        }

        /// <summary>
        /// Gets or sets the y vector for the correlation check.
        /// </summary>
        /// <value>The y vector for the correlation check.</value>
        public GeneralVector Y
        {
            get { return this.y; }
            set { this.y = value; }
        }

        /// <summary>
        /// Computes the correlation coefficient.
        /// </summary>
        /// <returns>The correlation coefficient.</returns>
        public double ComputeCorrelationCoefficient()
        {
            if (this.x.Count != this.y.Count)
            {
                throw new ArgumentException("The number of components of x and y have to be even.");
            }

            double sumX = 0;
            double sumY = 0;
            double sumXY = 0;
            double avgX = Arrays.Avg(this.x.VectorData);
            double avgY = Arrays.Avg(this.x.VectorData);

            for (int i = 0; i < this.x.Count; i++)
            {
                double tempuriX = this.x[i] - avgX;
                double tempuriY = this.y[i] - avgY;

                sumX += Math.Pow(tempuriX, 2);
                sumY += Math.Pow(tempuriY, 2);
                sumXY += tempuriX*tempuriY;
            }

            return sumXY/Math.Sqrt(sumX*sumY);
        }
    }
}